// pages/volunteer/publish.js
Page({
  data: {
    // 用户信息
    userInfo: {
      name: '晴天',
      volunteerId: '123444890',
      avatar: ''
    },
    
    // 内容相关
    content: '',
    images: [],
    
    // 话题标签
    topics: [
      { id: 1, name: '遗体捐献', selected: false },
      { id: 2, name: '志愿服务', selected: false },
      { id: 3, name: '公益活动', selected: false },
      { id: 4, name: '生命教育', selected: false },
      { id: 5, name: '爱心传递', selected: false },
      { id: 6, name: '志愿者日记', selected: false }
    ],
    
    // 位置信息
    location: '',
    
    // 发布设置
    syncToMoments: false,
    privacy: 'public', // public, friends, private
    privacyText: '所有人',
    
    // 发布状态
    canPublish: false
  },

  onLoad(options) {
    this.loadUserData();
  },

  // 加载用户数据
  loadUserData() {
    const userData = wx.getStorageSync('volunteerUserData') || {};
    this.setData({
      userInfo: { ...this.data.userInfo, ...userData }
    });
  },

  // 内容输入
  onContentInput(e) {
    const content = e.detail.value;
    this.setData({ 
      content,
      canPublish: content.trim().length > 0 || this.data.images.length > 0
    });
  },

  // 添加图片
  addImage() {
    const remainingCount = 9 - this.data.images.length;
    wx.chooseImage({
      count: remainingCount,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const newImages = [...this.data.images, ...res.tempFilePaths];
        this.setData({ 
          images: newImages,
          canPublish: this.data.content.trim().length > 0 || newImages.length > 0
        });
      }
    });
  },

  // 删除图片
  deleteImage(e) {
    const index = e.currentTarget.dataset.index;
    const images = [...this.data.images];
    images.splice(index, 1);
    this.setData({ 
      images,
      canPublish: this.data.content.trim().length > 0 || images.length > 0
    });
  },

  // 预览图片
  previewImage(e) {
    const index = e.currentTarget.dataset.index;
    wx.previewImage({
      current: this.data.images[index],
      urls: this.data.images
    });
  },

  // 切换话题
  toggleTopic(e) {
    const id = e.currentTarget.dataset.id;
    const topics = this.data.topics.map(topic => {
      if (topic.id === id) {
        return { ...topic, selected: !topic.selected };
      }
      return topic;
    });
    this.setData({ topics });
  },

  // 选择位置
  selectLocation() {
    wx.chooseLocation({
      success: (res) => {
        this.setData({ location: res.name });
      },
      fail: () => {
        wx.showToast({
          title: '位置选择失败',
          icon: 'none'
        });
      }
    });
  },

  // 同步设置
  onSyncChange(e) {
    this.setData({ syncToMoments: e.detail.value });
  },

  // 选择隐私设置
  selectPrivacy() {
    wx.showActionSheet({
      itemList: ['所有人', '仅好友', '仅自己'],
      success: (res) => {
        const privacyOptions = ['public', 'friends', 'private'];
        const privacyTexts = ['所有人', '仅好友', '仅自己'];
        this.setData({
          privacy: privacyOptions[res.tapIndex],
          privacyText: privacyTexts[res.tapIndex]
        });
      }
    });
  },

  // 发布推文
  publishPost() {
    if (!this.data.canPublish) {
      wx.showToast({
        title: '请输入内容或添加图片',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({ title: '发布中...' });

    // 模拟发布过程
    setTimeout(() => {
      // 保存推文数据
      const post = {
        id: Date.now(),
        content: this.data.content,
        images: this.data.images,
        topics: this.data.topics.filter(t => t.selected),
        location: this.data.location,
        privacy: this.data.privacy,
        syncToMoments: this.data.syncToMoments,
        createTime: new Date().toISOString(),
        userInfo: this.data.userInfo
      };

      // 保存到本地存储
      const posts = wx.getStorageSync('volunteerPosts') || [];
      posts.unshift(post);
      wx.setStorageSync('volunteerPosts', posts);

      // 更新用户积分
      const userData = wx.getStorageSync('volunteerUserData') || {};
      userData.currentPoints = (userData.currentPoints || 0) + 30;
      userData.totalPoints = (userData.totalPoints || 0) + 30;
      wx.setStorageSync('volunteerUserData', userData);

      // 记录任务完成
      this.completePublishTask();

      wx.hideLoading();
      wx.showToast({
        title: '发布成功 +30积分',
        icon: 'success'
      });

      // 返回上一页
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }, 2000);
  },

  // 完成任务
  completePublishTask() {
    const taskRecords = wx.getStorageSync('completedTasks') || [];
    const today = new Date().toDateString();
    
    // 检查今日是否已发布
    const todayPosts = taskRecords.filter(record => 
      record.taskId === 'publish' && record.date === today
    );

    if (todayPosts.length === 0) {
      taskRecords.push({
        taskId: 'publish',
        date: today,
        points: 30
      });
      wx.setStorageSync('completedTasks', taskRecords);
    }
  },

  // 返回
  goBack() {
    if (this.data.content.trim().length > 0 || this.data.images.length > 0) {
      wx.showModal({
        title: '提示',
        content: '确定要放弃编辑吗？',
        success: (res) => {
          if (res.confirm) {
            wx.navigateBack();
          }
        }
      });
    } else {
      wx.navigateBack();
    }
  },

  // 分享
  onShareAppMessage() {
    return {
      title: '分享志愿活动心得',
      path: '/pages/volunteer/publish',
      imageUrl: '/images/share-publish.png'
    };
  }
});